<template>
	<view class="scanCode-container"></view>
</template>

<script>
	export default {
		name: "scanCode",
		data() {
			return {
				activity: null,
				intentFilter: null, // 意图过滤器
				receiver: null, // 广播接收器
			};
		},
		created() {
			this.initScan();
			setTimeout(() => {
				this.startScan();
			}, 1000)
		},
		onHide() {
			this.stopScan();
		},
		destroyed() {
			// 页面退出时一定要卸载监听,否则下次扫描时结果会重复，造成扫一次出2个以上的结果或者结果会不断连续叠加
			this.stopScan();
		},
		methods: {
			//发送广播
			// ksguangbo() { 
			// 	var Intent = plus.android.importClass("android.content.Intent");
			// 	var intent = new Intent("com.android.server.scannerservice.broadcast");
			// 	var keyValue = "231112312";
			// 	var main = plus.android.runtimeMainActivity();
			// 	intent.putExtra("key", keyValue);
			// 	main.sendBroadcast(intent);
			// },
			initScan() {
				let _this = this;
				_this.activity = plus.android.runtimeMainActivity(); // 获取运行时的主要活动activity
				const IntentFilter = plus.android.importClass('android.content.IntentFilter'); // 导入类
				_this.intentFilter = new IntentFilter(); //实例化一个意图过滤器
				// addAction添加动作, com.android.server.scannerservice.broadcast为设备配置的广播名称
				_this.intentFilter.addAction('com.android.server.scannerservice.broadcast');

				// 蓝牙
				//var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				//var BAdapter = new BluetoothAdapter.getDefaultAdapter();
				// _this.intentFilter.addAction(BAdapter.ACTION_STATE_CHANGED); //监听蓝牙

				// BroadcastReceiver广播接收器接口
				// implements 实现接口  onReceive实现接口的方法
				_this.receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: function(context, intent) {
						plus.android.importClass(intent);
						let result = intent.getStringExtra('scannerdata'); // 手持机pda的广播键值 
						console.log('手持机pda的广播原始数据', result);
						_this.sendCode(result);
					},
				});
			},
			// 开始扫描
			startScan() {
				this.activity.registerReceiver(this.receiver, this.intentFilter);
				console.log('开始扫描', this.receiver);
			},
			// 结束扫描
			stopScan() {
				this.activity.unregisterReceiver(this.receiver);
			},
			sendCode(data) {
				// 防重复
				if (_codeQueryTag) return false;
				_codeQueryTag = true;
				setTimeout(function() {
					_codeQueryTag = false;
				}, 150);
				uni.$emit('scanCodeDate', { code: data });
			}
		}
	}
</script>

<style lang="scss">

</style>